<template>
  <div :class="{'flexStar':!isFile, 'up-down': isUpDown}">
    <template v-for="(item, index) in value">
      <div :key="item.fileId" class="marright10 imgBox" v-if="!isFile">
        <img
          ref="ylImage"
          class="pic imgList"
          :src="item.doc_url"
          v-if="!isVideoFile(item.doc_url)"
          :style="{
            width: width + 'px',
            height: (height ? height : width) + 'px',
            lineHeight: (height ? height : width) + 'px',
          }"
        />
        <video
          :src="item.doc_url"
          v-if="isVideoFile(item.doc_url)"
          :style="{
            width: width + 'px',
            height: (height ? height : width) + 'px',
            lineHeight: (height ? height : width) + 'px',
          }"
        ></video>
        <div class="layer" :style="{width: width + 'px', height: (height ? height : width) + 'px'}" v-if="!isImgSee">
          <span class="upload-wrapper-del check" @click.stop="() => preview = index" >
            <i class="el-icon-zoom-in"></i>
          </span>
          <span class="upload-wrapper-del delete" @click.stop="handleRemove(index)" >
            <i class="el-icon-delete"></i>
          </span>
        </div>
      </div>
    </template>
    <el-image-viewer style="z-index: 9999;" v-if="preview != -1" :url-list="previewList" :initialIndex="preview" :on-close="() => preview = -1"></el-image-viewer>
    <el-upload
      v-if="!limitNum || value.length < limitNum"
      v-loading="loading"
      action="#"
      :http-request="httpRequest"
      :class="{'pic-uploader-component':!isFile}"
      :style="{ width:!isFile?width + 'px':'', height:!isFile?(height ? height : width) + 'px':'' }"
      v-show="value.length <= 20"
      :show-file-list="false"
      :multiple="true"
      :before-upload="beforeAvatarUpload"
    >
    <el-button v-if="isFile" size="small" type="primary">添加附件</el-button>
      <i
       v-if="!isFile && !isImgSee"
        class="el-icon-plus pic-uploader-icon"
        :style="{
          width: width + 'px',
          height: (height ? height : width) + 'px',
          lineHeight: (height ? height : width) + 'px',
        }"
      ></i>
    </el-upload>
    <div v-if="isFile" class="fileGroup">
      <div class="fileList"  v-for="(item, index) in value" :key="item.fileId">
        <div class="name">{{item.fileName}}</div>
        <i class="el-icon-circle-close"  @click.stop="handleRemove(index)"></i>
      </div>
    </div>
  </div>
</template>

<script>
// :action="resourcesUrl + '/inf-bridge-service/back/storage/file/upload'" :headers="{Authorization: token}"
import { array } from "jszip/lib/support";
import _axios from "@/api/axios";
// 导入组件
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
    
export default {
  components: { ElImageViewer },
  data() {
    return {
      resourcesUrl: "",
      token: "",
      loading: false,
      preview: -1, // 是否郁兰图片
    };
  },
  props: {
    value: {
      default: "",
      type: array,
    },
    // 文件大小
    limitSize: {
      default: 10,
      type: [Number, String],
    },
    // 是否校验比例
    sizeVisible: {
      default: false,
      type: Boolean,
    },
    // 占位大小
    width: {
      default: 94,
      type: Number,
    },
    height: {
      default: 94,
      type: Number,
    },
    // 比例
    proportion: {
      default: 1,
      type: [Number, String],
    },
    limitNum: {
      type: Number,
      default: 0,
    },
    // 是否支持视频上传
    video: {
      type: Number,
      default: 0,
    },
    // 是否是上传文件
    isFile:{
      default: false,
      type: Boolean,
    },
    //是否详情展示不要上传
    isImgSee:{
      default: false,
      type: Boolean,
    },
    // 是否上下结构
    isUpDown: {
      type: Boolean,
      defalut: () => false
    }
  },
  created() {
    this.resourcesUrl = process.env.VUE_APP_BASE_API;
    this.token = 'bearer ' + localStorage.getItem("token");
  },
  computed: {
    previewList() {
      return this.value.map(item => item.doc_url)
    }
  },
  methods: {
    httpRequest(row) {
      let formData = new FormData();
      formData.append("file", row.file);
      _axios({
        headers: { Authorization: this.token },
        method: "post",
        url: this.resourcesUrl + "api/file/upload",
        data: formData,
      })
        .then((res) => {
          console.log(res, "res");
          let arr = [...this.value, res];
          if (this.limitNum > 0) {
            arr.splice(this.limitNum, arr.length - this.limitNum);
          }
          this.$emit("input", arr);
        })
        .catch((error) => {
          this.$message.error("上传图片失败");
        });
    },
    handleUploadProgress(e, file, fileList) {
      this.loading = true;
    },
    handleUploadError(err, file, fileList) {
      this.loading = false;
    },
    // 限制图片上传大小
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < parseInt(this.limitSize);
      if (!isLt2M) {
        this.$message.error(`上传图片大小不能超过 ${this.limitSize}MB!`);
        return false;
      }
      if (this.sizeVisible) {
        const isSize = new Promise(function (resolve, reject) {
          let _URL = window.URL || window.webkitURL;
          let image = new Image();
          image.onload = function () {
            let valid = image.width / image.height === (this.proportion || 1);
            valid ? resolve() : reject();
          };
          image.src = _URL.createObjectURL(file);
        }).then(
          () => {
            return file;
          },
          () => {
            this.$message.error("上传头像图片尺寸不符合");
            return Promise.reject(false);
          }
        );
        let typeArr = file.name.split(".");
        const fileType = typeArr[typeArr.length - 1].toLowerCase();
        const fileTypeStr = "jpg,png,jpeg";
        if (fileTypeStr.indexOf(fileType) < 0 && !this.video) {
          this.$message.warning("图片格式只能为jpg或png");
          return false;
        }
        return isSize;
      } else {
        let typeArr = file.name.split(".");
        const fileType = typeArr[typeArr.length - 1].toLowerCase();
        const fileTypeStr = "jpg,png,jpeg";
        if (fileTypeStr.indexOf(fileType) < 0 && !this.video) {
          this.$message.warning("图片格式只能为jpg或png");
          return false;
        }
      }
      return isLt2M;
    },
    // 移除
    handleRemove(index) {
      this.$emit("delteImage", index);
    },
    // 获取文件格式
    getTypeByFilePath(path) {
      if (path != undefined) {
        return path.substring(path.lastIndexOf("."), path.length);
      }
    },
    // 是否是视频
    isVideoFile(path) {
      let videos = [".mp4", ".ogg", ".webm"];
      return videos.includes(this.getTypeByFilePath(path));
    },
  },
};
</script>

<style lang="scss" scoped>
.up-down{
  width: 100%;
}
.flexStar {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
}
.marright10 {
  margin-right: 8px;
}
.imgList {
  border-radius: 3px;
  cursor: pointer;
}
.imgBox {
  position: relative;
  .layer{
    position: absolute;
    left: 0;
    top: 0;
    border-radius: 3px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  &:hover {
    .layer{
      background: rgba($color: #000000, $alpha: 0.5);
    }
    .delete {
      display: block;
      margin-left: 12px;
    }
    .check{
      display: block;
    }
  }
  .delete, .check {
    cursor: pointer;
    display: none;
  }
}
</style>
<style lang="scss">
.pic-uploader-component .el-upload {
  border: 1px solid #DCDFE6;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  .pic-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 104px;
    height: 104px;
    line-height: 104px;
    text-align: center;
  }

  .pic {
    width: 104px;
    height: 104px;
    display: block;
  }
}

.pic-uploader-component {
  width: 104px;
  height: 104px;
  margin-bottom: 8px;
}

.pic-uploader-component .el-upload:hover {
  border-color: #409eff;
}

.upload-wrapper-del {
  // position: relative;
  // background: rgba($color: #000000, $alpha: 0.5);
  // border-radius: 3px;

  i {
    color: #fff;
    font-size: 18px;
  }
}
// 新增附件类型
.fileGroup{
  margin-top:4px;
  .fileList{
    line-height:22px;
    margin-top:4px;
    display:flex;
    justify-content:space-between;
    align-items:center;
    .name{
      color: rgba(0,0,0,0.65);
    }
    i{
      color:#17B4A4;
      cursor:pointer;
    }
  }
  
}
</style>
